package com.zr.service.impl;


import com.zr.dto.RoleDTO;
import com.zr.dto.UserDTO;
import com.zr.entity.Role;
import com.zr.entity.User;
import com.zr.enums.CoreExceptionEnum;
import com.zr.exception.ServiceException;
import com.zr.service.IAuthService;
import com.zr.mapper.AuthMapper;
import com.zr.utils.BeanHelper;
import com.zr.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author: peterChen
 * @date: 2019/11/12 19:14
 * @description:
 * @version: 1.0
 */
@Slf4j
@Service
public class AuthServiceImpl implements IAuthService {
    @Autowired
    private AuthMapper authMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 登录
     * @param userVO
     */
    @Override
    public void login(UserVO userVO) {
        User u = new User();
        u.setUsername(userVO.getUsername());
        //1.1 查询用户
        User user = authMapper.selectOne(u);
        //1.2 判断用户是否存在
        if(user == null){
            log.error("不存在该用户！");
            throw new ServiceException(CoreExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //2.校验密码是否匹配
        if(!passwordEncoder.matches(userVO.getPassword(),user.getPassword())){
            //密码不匹配。抛出异常
            log.error("用户密码错误！");
            throw new ServiceException(CoreExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
    }



    @Override
    public void register(String username, String password) {
        User u = new User();
        u.setUsername(username);
        //1.1 查询用户
        User user = authMapper.selectOne(u);
        //1.2 判断用户是否存在
        if(user != null){
            log.error("该用户已添加！");
            throw new ServiceException(CoreExceptionEnum.INSERT_OPERATION_FAIL);
        }
        String encode = passwordEncoder.encode(password);
        u.setPassword(encode);
        int i = authMapper.insertSelective(u);
        if(i == 0){
            log.error("用户添加失败！");
            throw new ServiceException(CoreExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    @Override
    public UserDTO selectDtoByLoginName(String username) {
        User u = new User();
        u.setUsername(username);
        //根据用户名获取用户信息
        User user = authMapper.selectOne(u);
        if(user == null){
            log.error("用户信息不存在！");
            throw new ServiceException(CoreExceptionEnum.INVALID_PARAM_ERROR);
        }
        UserDTO userDTO = BeanHelper.copyProperties(user, UserDTO.class);
        //根据用户id获取角色信息
        Set<Role> roles = authMapper.selectRolesByUserId(user.getId());
        userDTO.setRoles(BeanHelper.copyWithCollection(roles,RoleDTO.class));
        return userDTO;
    }
}
